package edu.xidian.bdilab.jrbigdata.service.enterprise.productCheck.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonResponse;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.xidian.bdilab.jrbigdata.controller.bank.BankCode;
import edu.xidian.bdilab.jrbigdata.controller.government.GovernmentCode;
import edu.xidian.bdilab.jrbigdata.controller.response.ResponseResult;
import edu.xidian.bdilab.jrbigdata.domain.BankInfo;
import edu.xidian.bdilab.jrbigdata.domain.EnterpriseInfo;
import edu.xidian.bdilab.jrbigdata.domain.FinancialProduct;
import edu.xidian.bdilab.jrbigdata.domain.ProductRequest;
import edu.xidian.bdilab.jrbigdata.mapper.BankInfoMapper;
import edu.xidian.bdilab.jrbigdata.mapper.EnterpriseInfoMapper;
import edu.xidian.bdilab.jrbigdata.mapper.FinancialProductMapper;
import edu.xidian.bdilab.jrbigdata.mapper.ProductRequestMapper;
import edu.xidian.bdilab.jrbigdata.service.enterprise.productCheck.ProductCheckService;
//import org.omg.CORBA.INTERNAL;
import edu.xidian.bdilab.jrbigdata.util.AliyunConfigUtil;
import edu.xidian.bdilab.jrbigdata.util.GuavaCacheUtil;
import edu.xidian.bdilab.jrbigdata.util.MessageUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;

/**
 * @ClassName ProductCheckServiceImpl
 * @Description TODO
 * @Author tuantuan
 * @Date 2019/3/30 下午9:36
 * @Version 1.0
 * @Attention Copyright (C), 2004-2019, BDILab, XiDian University
 **/
@Service
public class ProductCheckServiceImpl implements ProductCheckService {
    @Autowired
    FinancialProductMapper financialProductMapper;
    @Autowired
    ProductRequestMapper productRequestMapper;

    @Autowired
    private BankInfoMapper bankInfoMapper;

    @Autowired
    private EnterpriseInfoMapper enterpriseInfoMapper;


    @Override
    public List<FinancialProduct> checkProduct(Integer institution_type, Integer loanLimit, Integer loan_period,
                                              Integer guarantee_mode, Integer internet_loan_type, Integer product_properties, String socialCode) {

//        FinancialProduct financialProduct;
        QueryWrapper<FinancialProduct> productQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ProductRequest> requestQueryWrapper = new QueryWrapper<>();

        ArrayList<FinancialProduct> financialProductList;
        ArrayList<ProductRequest> requestList;
        ArrayList<String> requestProductName = new ArrayList<>();

        //先查出来金融产品
        productQueryWrapper.eq(institution_type!=null,"institution_type", institution_type)
                .eq(loanLimit!=null,"loan_limit", loanLimit)
                .like(loan_period!=null,"loan_period", loan_period)
                .eq(guarantee_mode!=null,"guarantee_mode", guarantee_mode)
                .eq(internet_loan_type!=null,"internet_loan_type", internet_loan_type)
                .eq(product_properties!=null,"product_properties", product_properties);

        //查出来企业已有的产品申请
        requestQueryWrapper.eq("fk_social_code",socialCode);
        requestList = (ArrayList<ProductRequest>) productRequestMapper.selectList(requestQueryWrapper);
        for(ProductRequest productRequest: requestList){
            productQueryWrapper.ne("product_name", productRequest.getFkProductName());
        }

        financialProductList = (ArrayList<FinancialProduct>) financialProductMapper.selectList(productQueryWrapper);

        return financialProductList;
    }

    /**
     * 发送阿里云短信
     * @Auther: wangfs
     * @param
     * @return
     */
    @Override
    public ResponseResult sendAliyunMsg(String fkBankId, String socialCode)  {
        ResponseResult responseResult = new ResponseResult();
        /**
         * 1.查询银行信息
         */
        QueryWrapper<BankInfo> queryWrapper = new QueryWrapper<BankInfo>();
        queryWrapper.lambda().eq(BankInfo::getBankId,fkBankId);
        BankInfo bankInfo = bankInfoMapper.selectOne(queryWrapper);

        if(null == bankInfo || StringUtils.isEmpty(bankInfo.getContactPhone())){
            responseResult.setCode(BankCode.CHENCK_FAILED.getCode());
            responseResult.setMessage("未获取到银行信息");
            responseResult.setSuccess(FALSE);
            return responseResult;
        }

        if(!validateMobilePhone(bankInfo.getContactPhone())){
            responseResult.setCode(BankCode.CHENCK_FAILED.getCode());
            responseResult.setMessage("座机无法发送短信");
            responseResult.setSuccess(FALSE);
            return responseResult;
        }

        /**
         * 2.获取企业信息
         */
        QueryWrapper<EnterpriseInfo> queryWrapperTwo = new QueryWrapper<EnterpriseInfo>();
        queryWrapperTwo.lambda().eq(EnterpriseInfo::getSocialCode,socialCode);

        EnterpriseInfo enterpriseInfo = enterpriseInfoMapper.selectOne(queryWrapperTwo);
        if(null == enterpriseInfo){
            responseResult.setCode(BankCode.CHENCK_FAILED.getCode());
            responseResult.setMessage("未获取到企业信息");
            responseResult.setSuccess(FALSE);
            return responseResult;
        }

        /**
         * 发送验证码
         */
        Map<String,String> param = new HashMap<>();
        param.put("name",enterpriseInfo.getEnterpriseName());
        CommonResponse commonResponse = MessageUtil.aliyunsendSms(AliyunConfigUtil.APP_ID,AliyunConfigUtil.APP_SECRET,bankInfo.getContactPhone(),
                AliyunConfigUtil.SIGNNAME,AliyunConfigUtil.TEMPLATE_CODE_SEND_BANK_CODE, param);
        JSONObject json = JSONObject.parseObject(commonResponse.getData());
        String resultCode =(String)json.get("Code");
        String message =(String)json.get("Message");
        if("OK".equals(resultCode) && "OK".equals(message)){
            responseResult.setSuccess(true);
            responseResult.setCode(GovernmentCode.SEND_CODE_SUCCESS.getCode());
            responseResult.setMessage("短信通知已发送");
            return responseResult;
        }

        responseResult.setData(true);
        responseResult.setCode(BankCode.CHECK_SUCCESS.getCode());
        responseResult.setMessage("短信通知已发送");
        responseResult.setSuccess(TRUE);



        return responseResult;
    }

    /**
     *  正则：手机号（简单）, 1字头＋10位数字即可.
     * @param in
     * @return
     */
    public static boolean validateMobilePhone(String in) {
        Pattern pattern = Pattern.compile("^[1]\\d{10}$");
        return pattern.matcher(in).matches();
    }

}
